package io.renren.modules.erp.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.renren.common.constants.BusinessConstants;
import io.renren.common.constants.ExceptionConstants;
import io.renren.common.exception.BusinessRunTimeException;
import io.renren.common.utils.Constants;
import io.renren.common.utils.QueryUtils;
import io.renren.common.utils.R;
import io.renren.common.utils.StringUtil;
import io.renren.modules.erp.entity.Account;
import io.renren.modules.erp.service.AccountService;
import io.renren.modules.erp.service.impl.AccountServiceImpl;
import io.renren.modules.erp.vo.AccountVo4InOutList;
import io.renren.modules.sys.controller.AbstractController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/account")
public class AccountController extends AbstractController {
    private Logger logger = LoggerFactory.getLogger(AccountController.class);

    @Autowired
    private AccountService accountService;
    @GetMapping(value = "/list")
    public  R getAccountList(@RequestParam Map<String, String> params) throws Exception{
        String search = params.get(Constants.SEARCH);
        String name = StringUtil.getInfo(search, "name");
        String serialNo = StringUtil.getInfo(search, "serialNo");
        String remark = StringUtil.getInfo(search, "remark");
        String order = QueryUtils.order(params);
        int pageSize = Integer.valueOf(params.get( "pageSize"));
        int currPage = Integer.valueOf(params.get( "currentPage"));
        return R.ok().put("data",accountService.select(name, serialNo, remark,currPage, pageSize));
    }


    /**
     * 查找结算账户信息-下拉框
     * @param request
     * @return
     */
    @GetMapping(value = "/findBySelect")
    public String findBySelect(HttpServletRequest request) throws Exception {
        String res = null;
        try {
            List<Account> dataList = accountService.findBySelect();
            //存放数据json数组
            JSONArray dataArray = new JSONArray();
            if (null != dataList) {
                for (Account account : dataList) {
                    JSONObject item = new JSONObject();
                    item.put("Id", account.getId());
                    //结算账户名称
                    item.put("AccountName", account.getName());
                    dataArray.add(item);
                }
            }
            res = dataArray.toJSONString();
        } catch(Exception e){
            e.printStackTrace();
            res = "获取数据失败";
        }
        return res;
    }

    /**
     * 获取所有结算账户
     * @param request
     * @return
     */
    @GetMapping(value = "/getAccount")
    public R getAccount(HttpServletRequest request) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
            List<Account> accountList = accountService.getAccount();
            map.put("accountList", accountList);
            return R.ok().put("data",map);
    }

    /**
     * 账户流水信息
     * @param currentPage
     * @param pageSize
     * @param accountId
     * @param initialAmount
     * @param request
     * @return
     */
    @GetMapping(value = "/findAccountInOutList")
    public R findAccountInOutList(@RequestParam("currentPage") Integer currentPage,
                                                 @RequestParam("pageSize") Integer pageSize,
                                                 @RequestParam("accountId") Long accountId,
                                                 @RequestParam("initialAmount") BigDecimal initialAmount,
                                                 HttpServletRequest request) throws Exception{
            return R.ok().put("data",accountService.findAccountInOutList(accountId, currentPage, pageSize,initialAmount));

    }


    @PostMapping(value = "/updateAmountIsDefault")
    public R updateAmountIsDefault(@RequestParam("isDefault") Boolean isDefault,
                                 @RequestParam("accountId") Long accountId,
                                 HttpServletRequest request) throws Exception{
        int res = accountService.updateAmountIsDefault(isDefault, accountId);
        if(res > 0) {
            return R.ok();
        } else {
            return R.error();
        }
    }
    /**
     *  批量删除账户信息
     * create time: 2019/3/29 10:49
     * @Param: ids
     * @return java.lang.Object
     */
    @RequestMapping(value = "/batchDeleteAccountByIds")
    public R batchDeleteAccountByIds(@RequestParam("ids") String ids,@RequestParam(value="deleteType",
            required =false,defaultValue= BusinessConstants.DELETE_TYPE_NORMAL)String deleteType) throws Exception {

        int i=0;
        if(BusinessConstants.DELETE_TYPE_NORMAL.equals(deleteType)){
             i= accountService.batchDeleteAccountByIdsNormal(ids,getUserId());
        }else if(BusinessConstants.DELETE_TYPE_FORCE.equals(deleteType)){
             i= accountService.batchDeleteAccountByIds(ids,getUserId());
        }else{
            logger.error("异常码[{}],异常提示[{}],参数,ids[{}],deleteType[{}]",
                    ExceptionConstants.DELETE_REFUSED_CODE,ExceptionConstants.DELETE_REFUSED_MSG,ids,deleteType);
            throw new BusinessRunTimeException(ExceptionConstants.DELETE_REFUSED_CODE,
                    ExceptionConstants.DELETE_REFUSED_MSG);
        }
        if(i<1){
            logger.error("异常码[{}],异常提示[{}],参数,ids[{}]",
                    ExceptionConstants.ACCOUNT_DELETE_FAILED_CODE,ExceptionConstants.ACCOUNT_DELETE_FAILED_MSG,ids);
            throw new BusinessRunTimeException(ExceptionConstants.ACCOUNT_DELETE_FAILED_CODE,
                    ExceptionConstants.ACCOUNT_DELETE_FAILED_MSG);
        }
        return R.ok();
    }

    /**
     * 结算账户的统计
     * @param request
     * @return
     */
    @GetMapping(value = "/getStatistics")
    public R getStatistics(HttpServletRequest request) throws Exception {
            Map<String, Object> map = accountService.getStatistics();
            return R.ok().put("data",map);
    }

    @PostMapping(value = "/add")
    public R insert(@RequestBody String beanJson, HttpServletRequest request) throws Exception{
        if(1==accountService.insertAccount(beanJson, request)){
            return R.ok();
        }else{
            return R.error();
        }
    }

    @PostMapping(value = "/update")
    public R update(@RequestBody String beanJson,@RequestParam("id") Long id, HttpServletRequest request)throws Exception {
        if(1==accountService.updateAccount(beanJson, id, request)){
            return R.ok();
        }else{
            return R.error();
        }
    }

    @GetMapping(value = "/delete")
    public R delete(@RequestParam("id") Long id, HttpServletRequest request)throws Exception {
        if(1==accountService.deleteAccount(id, request)){
            return R.ok();
        }else{
            return R.error();
        }
    }

    @GetMapping(value = "/batchDelete")
    public R batchDelete(@RequestParam("ids") String ids, HttpServletRequest request)throws Exception {
        if(1==accountService.batchDeleteAccount(ids, request)){
            return R.ok();
        }else{
            return R.error();
        }
    }

    @GetMapping(value = "/checkIsNameExist")
    public R checkIsNameExist(@RequestParam("id") Long id, @RequestParam("name") String name)throws Exception {
        if(0<accountService.checkIsNameExist(id, name)){
            return R.ok();
        }else{
            return R.error();
        }
    }


}
